package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Notice;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.NoticeMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.INoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TravelMapper travelMapper;


    @Override
    public int deleteByPrimaryKey(Long id) {
        return noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Notice selectByPrimaryKey(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<Notice> queryForList(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Notice> list = noticeMapper.queryForList(qo);
        return new PageInfo<>(list);
    }


    @Override
    public void saveOrUpdate(Notice record) {
        List<User> users = userMapper.selectAll();
        //判断状态,如果发布,则添加发布时间
        if (record.getState() == 1) {
            record.setReleaseTime(new Date());
        }
        if (record.getId() != null) {
            noticeMapper.updateByPrimaryKey(record);
        } else {
            noticeMapper.insert(record);
            for(User u:users){
                noticeMapper.insertRelationWithUser(record.getId(),u.getId());
            }

        }
    }

    @Override
    public void saveNoticeForAuthor(Long travelId) {
        //获得作者id
        Long  userId=travelMapper.selectAuthorIdBytravelId(travelId);
        Notice notice=new Notice();
        notice.setTitle("游记审核结果");
        notice.setContent("<p>您的游记审核通过啦,真是一件举国欢腾的是呢!</p>对了,悄悄跟你说哟,现在有一大波小驴驴们正奔向您的新游记,请注意安全!");
        notice.setState(1);
        notice.setReleaseTime(new Date());
        noticeMapper.insert(notice);
        noticeMapper.insertRelationWithUser(notice.getId(),userId);
    }

}
